package ufs.cmds;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import ufs.file.UfsStream;

public class ufs_mount {

	public static void main(String[] args) {
		
		UfsStream ufsStream = new UfsStream(UFSCommandsConstants.nameFile);

		boolean exists = ufsStream.exists();
		if(exists == false) {
			System.out.println( UFSCommandsConstants.FS_DOES_NOT_EXISTS );
			return;
		}

		ufsStream.seek(UFSCommandsConstants.BOOT_SECTOR_SIZE);
		
		int partitionIndicator = ufsStream.rInt();
		
		if(partitionIndicator == UFSCommandsConstants.MOUNTED_PARTITION) {
			
	        String [] params = null;
	        String classname = "ufs.ufsd";
	                
	                 Class<?> clazz;
					try {
						clazz = Class.forName(classname);
						  final Method main = clazz.getMethod("main", String[].class);    

			                main.invoke(null, new Object[]{params});
					} catch (ClassNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (SecurityException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (NoSuchMethodException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IllegalArgumentException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IllegalAccessException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (InvocationTargetException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
	              
	                
			
			System.out.println(UFSCommandsConstants.PARTITON_ALREADY_MOUNTED );
			return;
		}		
		if( partitionIndicator == UFSCommandsConstants.UNMOUNTED_PARTITION) {
			ufsStream.seek(UFSCommandsConstants.BOOT_SECTOR_SIZE);
			ufsStream.wInt(UFSCommandsConstants.MOUNTED_PARTITION);
			
			try {
				Runtime.getRuntime().exec("java D:\\Sviluppo\\Java\\j2ee\\workspace\\UFS\\target\\classes\\ufs\\ufsd");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			System.out.println(UFSCommandsConstants.MOUNT_OK);
			return;
		}
		
		System.out.println(UFSCommandsConstants.FAT_CORRUPTED);
		
	}
}
